<template>
  <je-modal
    v-model:visible="modalShow"
    width="200"
    height="auto"
    title="修改密码"
    class="je-admin-change-password"
    header-style="text-align:center"
    :maximizable="false"
    :closable="false"
    :ok-button="!authSuccess ? handOk : false"
    :cancel-button="!authSuccess"
    :on-close="changeModal"
  >
    <div v-if="!authSuccess">
      <div class="rule-prompt">{{ passwordRuleTip }}</div>
      <div class="reset-box">
        <div :class="{ 'force-div': validaErrorStatus.oldPassword }" style="margin-bottom: 20px">
          <je-password
            v-model:value="userSet.oldPassword"
            placeholder="原始密码"
            class="input-item"
            :style="{ border: validaErrorStatus.oldPassword ? '1px solid #ff625c' : '' }"
            @change="changeInfo('oldPassword')"
            @blur="changeInfo('oldPassword')"
          >
            <template #prefix>
              <i class="fal fa-lock" style="padding-right: 5px"></i>
            </template>
          </je-password>
        </div>
        <div :class="{ 'force-div': validaErrorStatus.newPassword }">
          <je-password
            v-model:value="userSet.newPassword"
            placeholder="新密码"
            class="input-item"
            :style="{ border: validaErrorStatus.newPassword ? '1px solid #ff625c' : '' }"
            @change="changeInfo('newPassword')"
            @blur="changeInfo('newPassword')"
          >
            <template #prefix>
              <i class="fal fa-lock" style="padding-right: 5px"></i>
            </template>
          </je-password>
        </div>
        <div class="auth-stren-box">
          <div class="stren-tip">{{ passwordRule }}</div>
          <div class="stren-progre">
            <div
              class="progre-item"
              :class="{
                'progre-part': ruleStepOne,
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
            <div
              class="progre-item"
              :class="{
                'progre-part': ruleStepOne && ruleStepTwo,
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
            <div
              class="progre-item"
              :class="{
                'progre-all': ruleStepOne && ruleStepTwo && ruleStepThree,
              }"
            ></div>
          </div>
        </div>
        <div :class="{ 'force-div': validaErrorStatus.confirmPassword }">
          <je-password
            v-model:value="userSet.confirmPassword"
            placeholder="确认密码"
            class="input-item"
            :style="{ border: validaErrorStatus.confirmPassword ? '1px solid #ff625c' : '' }"
            @change="changeInfo('confirmPassword')"
            @blur="changeInfo('confirmPassword')"
          >
            <template #prefix>
              <i class="fal fa-lock" style="padding-right: 5px"></i>
            </template>
          </je-password>
        </div>
        <div class="anth-error">{{ anthErrorMes }}</div>
      </div>
    </div>
    <div v-if="authSuccess" class="auth-success">
      <div class="auth-icon">
        <i class="jeicon jeicon-check-circle-s"></i>
      </div>
      <div class="success-tip">{{ handle.resetSuccess }}</div>
      <div class="success-time">{{ countDown }}S</div>
    </div>
  </je-modal>
</template>
<script>
  import { defineComponent, toRefs, reactive, onBeforeMount } from 'vue';
  import { Input, Modal } from '@jecloud/ui';
  import { useI18n } from '@common/locales';
  import { GetLoginPlans, editPassword } from './api/index';
  import { logout } from '@/helper/system';
  import { useRoute } from 'vue-router';
  import {
    passwordSimpleRegTempalte,
    passwordMedinmRegTempalte,
    passwordSimpleComplexTempalte,
    containsNumber,
    constainsLetter,
    constainsChars,
    constainsNumberAndChars,
    constainsNumberAndLetter,
    constainsLetterAndChars,
    constainsLowerLetterAndCharNum,
    constainsLargeLetterAndCharsNum,
  } from './js/common';
  import { PASSWORD_SAFE_STRATEgy } from './js/constant';
  import { useGlobalStore } from '@common/store/global-store';
  export default defineComponent({
    name: 'AdminChangePassword',
    components: {
      JePassword: Input.Password,
    },
    props: {
      visible: Boolean,
    },
    emits: ['closeModal'],
    setup(props, { emit }) {
      const route = useRoute();
      const t = useI18n().t;
      const globalStore = useGlobalStore();
      const { REGEXP_NUMBER, REGEXP } = globalStore.plans.get(globalStore.activePlan);
      const state = reactive({
        anthErrorMes: '',
        authSuccess: false,
        modalShow: props.visible,
        passwordRuleTip: `密码为${REGEXP_NUMBER}位以上${PASSWORD_SAFE_STRATEgy[REGEXP]}`,
        validaErrorStatus: {
          newPassword: false,
          confirmPassword: false,
          oldPassword: false,
        },
        ruleStepOne: false, //密码验证第一步
        ruleStepTwo: false, //密码验证第二步
        ruleStepThree: false, //密码验证第二步
        passwordRule: t('resetPassword.stepNull'), //输入密码规则提示
        handle: {
          submitBut: t('resetPassword.submitBut'),
          newPassword: t('resetPassword.newPassword'),
          confirmPassword: t('resetPassword.confirmPassword'),
          stepNull: t('resetPassword.stepNull'),
          stepOne: t('resetPassword.stepOne'),
          stepTwo: t('resetPassword.stepTwo'),
          stepThree: t('resetPassword.stepThree'),
          resetSuccess: t('resetPassword.resetSuccess'),
          emptyNewPassword: t('warnMessage.newPassword'),
          emptyConfirmPassword: t('warnMessage.confirmPassword'),
          fromatNewPassword: t('warnMessage.fromatNewPassword'),
          emptyOldpassword: t('warnMessage.emptyOldpassword'),
        },
        pl: REGEXP_NUMBER,
        userSet: {
          //用户设置新密码
          newPassword: '',
          confirmPassword: '',
          oldPassword: '',
        },
        countDown: 0, // 页面上显示的倒计时数字
        timerThree: null, // 倒计时的对象
      });
      const methods = {
        countDownFunc() {
          const TIME_COUNT = 3; // 3s的倒计时变量
          if (!state.timerThree) {
            // 没有倒计时在执行
            state.countDown = TIME_COUNT;
            state.timerThree = setInterval(() => {
              if (state.countDown > 1 && state.countDown <= TIME_COUNT) {
                state.countDown--;
              } else {
                clearInterval(state.timerThree); // 停止循环执行
                state.timerThree = null; // 倒计时对象置为null
                globalStore.historyRoute = route?.fullPath;
                window.localStorage.removeItem('userPassword');
                // 退出
                logout(true);
              }
            }, 1000); // 1s执行一次
          }
        },
        // 点击确定按钮
        handOk() {
          if (state.userSet.oldPassword == '') {
            state.anthErrorMes = state.handle.emptyOldpassword;
            state.validaErrorStatus.oldPassword = true;
            return false;
          } else {
            state.validaErrorStatus.oldPassword = false;
          }
          if (state.userSet.newPassword == '') {
            state.anthErrorMes = state.handle.emptyNewPassword;
            state.validaErrorStatus.newPassword = true;
            return false;
          } else {
            state.validaErrorStatus.newPassword = false;
          }
          if (!state.userSet.confirmPassword) {
            state.anthErrorMes = state.handle.emptyConfirmPassword;
            state.validaErrorStatus.confirmPassword = true;
            return false;
          } else {
            state.validaErrorStatus.confirmPassword = false;
          }
          if (state.userSet.newPassword !== state.userSet.confirmPassword) {
            state.anthErrorMes = state.handle.fromatNewPassword;
            return false;
          }
          const params = {
            oldPassword: state.userSet.oldPassword,
            newPassword: state.userSet.confirmPassword,
          };
          editPassword(params)
            .then(() => {
              state.authSuccess = true;
              methods.countDownFunc();
            })
            .catch((err) => {
              state.authSuccess = false;
              state.anthErrorMes = err.message;
              return false;
            });

          return false;
        },
        // 点击关闭按钮
        changeModal() {
          emit('closeModal');
        },
        // 监听原始密码、新密码、确认
        changeInfo(type) {
          switch (type) {
            case 'oldPassword':
              if (state.userSet.oldPassword) {
                state.anthErrorMes = '';
                state.validaErrorStatus.oldPassword = false;
              } else {
                state.anthErrorMes = state.handle.oldPassword;
                state.validaErrorStatus.oldPassword = true;
              }
              return;
            case 'newPassword': //监听新密码
              if (state.userSet.newPassword) {
                state.anthErrorMes = '';
                state.validaErrorStatus.newPassword = false;
              } else {
                state.anthErrorMes = state.handle.emptyNewPassword;
                state.validaErrorStatus.newPassword = true;
              }
              if (state.userSet.newPassword.length >= state.pl) {
                if (passwordSimpleComplexTempalte(state.pl).test(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = true;
                  state.passwordRule = state.handle.stepThree;
                  return;
                } else if (passwordMedinmRegTempalte(state.pl).test(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = state.handle.stepTwo;
                  return;
                } else if (passwordSimpleRegTempalte(state.pl).test(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = false;
                  state.ruleStepThree = false;
                  state.passwordRule = state.handle.stepOne;
                  return;
                } else if (containsNumber(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = false;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLetter(state.userSet.newPassword)) {
                  state.ruleStepOne.value = true;
                  state.ruleStepTwo = false;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneNumber');
                  return;
                } else if (constainsChars(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = false;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneNumber');
                  return;
                } else if (constainsNumberAndChars(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLetterAndChars(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneNumber');
                  return;
                } else if (constainsNumberAndLetter(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLargeLetterAndCharsNum(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneLetter');
                  return;
                } else if (constainsLowerLetterAndCharNum(state.userSet.newPassword)) {
                  state.ruleStepOne = true;
                  state.ruleStepTwo = true;
                  state.ruleStepThree = false;
                  state.passwordRule = t('resetPassword.noneLetter');
                  return;
                }
              } else {
                state.passwordRule = state.handle.stepNull;
                state.ruleStepOne = false;
                state.ruleStepTwo = false;
                state.ruleStepThree = false;
              }
              break;
            case 'confirmPassword': //监听确认密码
              if (state.userSet.newPassword) {
                if (state.userSet.confirmPassword) {
                  state.anthErrorMes = '';
                  state.validaErrorStatus.confirmPassword = false;
                } else {
                  state.anthErrorMes = state.handle.emptyConfirmPassword;
                  state.validaErrorStatus.confirmPassword = true;
                }
              }
              break;
            default:
              break;
          }
        },
        // 初始化获取平台的数据
        getInitConfig() {
          GetLoginPlans()
            .then((res) => {
              globalStore.plans.set(globalStore.activePlan, res.data);
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
            });
        },
      };
      onBeforeMount(() => {
        // 如果缓存里面没有数据的话，那么重新初始化获取平台的数据
        // 初始化配置信息
        const config = globalStore.plans.get(globalStore.activePlan);
        config == undefined && methods.getInitConfig();
      });
      return { ...methods, ...toRefs(state) };
    },
  });
</script>
<style lang="less" scoped>
  .je-admin-change-password {
    .input-item {
      border-radius: 2px;
      font-size: 12px;
      color: #a1a1a1;
      line-height: 46px;
      height: 46px;
    }
    text-align: center;
    .rule-prompt {
      width: 100%;
      height: 20px;
      line-height: 20px;
      text-align: center;
      color: #c0c4cc;
      font-size: 14px;
    }
    .reset-box {
      margin: 20px auto 0;
    }
    .auth-stren-box {
      width: 100%;
      padding-left: 12px;
      .stren-tip {
        height: 12px;
        font-size: 12px;
        line-height: 12px;
        color: #c0c4cc;
        margin-top: 10px;
        text-align: left;
      }
      .stren-progre {
        display: flex;
        margin: 6px auto 10px;
        .progre-item {
          width: 50px;
          height: 4px;
          background: #a9aba9;
          margin-right: 6px;
        }
        .progre-part {
          background: #f9a646;
        }
        .progre-all {
          background: #02a863;
        }
      }
    }
    .anth-error {
      width: 100%;
      height: 20px;
      line-height: 20px;
      font-size: 14px;
      color: #ff625c;
      text-align: center;
      margin-top: 20px;
    }
    .auth-success {
      width: 360px;
      margin: 10px auto 0;
      .auth-icon {
        width: 50px;
        height: 50px;
        margin: 0 auto;
        position: relative;
        i {
          font-size: 50px;
          color: #6dcc51;
          position: absolute;
          top: -14px;
        }
      }
      .success-tip {
        width: 100%;
        height: 20px;
        line-height: 20px;
        font-size: 20px;
        color: #3f3f3f;
        text-align: center;
        margin-top: 20px;
      }
      .success-time {
        font-size: 14px;
        color: #3f3f3f;
        text-align: center;
        margin-top: 20px;
      }
    }
    .auth-success {
      width: 360px;
      padding: 10px 0 50px;
      .auth-icon {
        width: 50px;
        height: 50px;
        margin: 0 auto;
        position: relative;
        i {
          font-size: 50px;
          color: #6dcc51;
          position: absolute;
          top: -14px;
        }
      }
      .success-tip {
        width: 100%;
        height: 20px;
        line-height: 20px;
        font-size: 20px;
        color: #3f3f3f;
        text-align: center;
        margin-top: 20px;
      }
    }
    .err-tip {
      width: 100%;
      height: 20px;
      margin-top: 40px;
      line-height: 20px;
      font-size: 14px;
      color: #ff625c;
      text-align: center;
    }
  }
</style>
<style>
  .input-item .ant-input-clear-icon {
    top: 12px !important;
  }
</style>
